package top.cardone.context.aspect;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.core.annotation.AnnotationUtils;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.context.annotation.Func;
import top.cardone.context.util.FuncUtils;
import top.cardone.core.util.func.Func2;

import java.util.Map;

/**
 * Created by yao hai tao on 2015/8/3.
 */
@Log4j2
public class FuncAspect {
    /**
     * 设置属性
     *
     * @param joinPoint 切片点
     */
    public Object func(final ProceedingJoinPoint joinPoint) throws Throwable {
        final java.lang.reflect.Method method = ((org.aspectj.lang.reflect.MethodSignature) joinPoint.getSignature()).getMethod();

        Func funcAnnotation = AnnotationUtils.findAnnotation(method, Func.class);

        if (funcAnnotation == null || StringUtils.isBlank(funcAnnotation.beanId())) {
            return joinPoint.proceed();
        }

        final Map<String, Object> configMap = FuncUtils.getMap(funcAnnotation);

        if (MapUtils.isEmpty(configMap)) {
            return joinPoint.proceed();
        }

        return ApplicationContextHolder.func(Func2.class, func2 -> func2.func(joinPoint, configMap), funcAnnotation.beanId());
    }
}
